<template>
  <div class="full-screen-container">
    <div class="action-bar">
      <el-button type="primary" @click="dialogVisible = true" class="cl1">新增预约</el-button>
    </div>

    <!-- 全屏表格容器 -->
    <div class="full-screen-table">
      <el-table
          :data="appointmentData"
          stripe
          style="width: 100%; height: calc(100vh - 170px)"
          :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontSize: '16px',
        }"
          :cell-style="{padding: '16px 0' }"
          v-loading="loading"
      >
        <el-table-column
            prop="id"
            label="ID"
            width="100"
            align="center"
        />
        <el-table-column
            prop="activity.activityName"
            label="服务名称"
            min-width="200"
        />
        <el-table-column
            prop="user.name"
            label="主人姓名"
            min-width="200"
        />
        <el-table-column
            prop="user.phone"
            label="联系电话"
            min-width="150"
        />
        <el-table-column
            prop="pet.petName"
            label="宠物名称"
            min-width="100"
        />
        <el-table-column
            prop="appointmentDate"
            label="预约日期"
            width="150"
            :formatter="formatDate"
        />
        <el-table-column
            prop="startTime"
            label="开始时间"
            width="150"
            :formatter="formatDate"
        />
        <el-table-column
            prop="endTime"
            label="结束时间"
            width="150"
            :formatter="formatDate"
        />

        <el-table-column label="预约状态" width="150">
          <template #default="scope">
            <el-tag :type="getStatus(scope.row) === 'active' ? 'success' : 'info'">
              {{ getStatus(scope.row) === 'active' ? '已预约' : '已结束' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="notes"
            label="备注"
            min-width="200"
            show-overflow-tooltip
        />
        <el-table-column>
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeAppointment(scope.row.id)">取消预约</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部固定分页 -->
    <div class="pagination-footer">
      <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" title="新增预约" width="600px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="主人姓名" prop="ownerName">
          <el-input v-model="form.ownerName" placeholder="请输入主人姓名" />
        </el-form-item>

        <el-form-item label="宠物名称" prop="petId">
          <el-select v-model="form.petId" placeholder="请选择宠物" :disabled="!form.ownerName">
            <el-option
                v-for="pet in pets"
                :key="pet.petsId"
                :label="pet.petName"
                :value="pet.petsId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="服务项目" prop="activityId">
          <el-select v-model="form.activityId" placeholder="请选择服务项目">
            <el-option
                v-for="activity in activities"
                :key="activity.id"
                :label="activity.activityName"
                :value="activity.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预约日期" prop="appointmentDate">
          <el-date-picker
              v-model="form.appointmentDate"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="时间段" prop="timeRange">
          <el-time-picker
              v-model="form.timeRange"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              :picker-options="timePickerOptions"
              :disabled="!form.activityId"
          />
          <div class="time-tip" v-if="selectedActivity">
            最大服务时长：{{ selectedActivity.durationText }}（{{ selectedActivity.duration }}分钟）
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisibles">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, watch, computed} from "vue";
import { useRouter } from "vue-router";
import api from "@/util/api.js";
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from "dayjs";

const router = useRouter();
const loading = ref(false);
const dialogVisible = ref(false);
const formRef = ref(null);


const getStatus = (appointment) => {
  if (!appointment.appointmentDate || !appointment.endTime) return 'inactive';

  const now = dayjs();
  const endDateTime = dayjs(
      `${appointment.appointmentDate} ${appointment.endTime}`,
      'YYYY-MM-DD HH:mm'
  );

  return now.isBefore(endDateTime) ? 'active' : 'inactive';
};


function dialogVisibles(){
  dialogVisible.value = false;
   form.value = {
     ownerName: "",
     customerId:"",
     petId: "",
     activityId: "",
     appointmentDate: "",
     timeRange: [], // 默认时间段
     notes: ""
   }
}

// 表单数据 - 使用ref创建响应式对象
const form = ref({
  ownerName: "",
  customerId:"",
  petId: "",
  activityId: "",
  appointmentDate: "",
  timeRange: [], // 默认时间段
  notes: ""
});

// 表单验证规则
const rules = ref({
  ownerName: [{ required: true, message: "请输入主人姓名", trigger: "blur" }],
  petId: [{ required: true, message: "请选择宠物", trigger: "change" }],
  activityId: [{ required: true, message: "请选择服务项目", trigger: "change" }],
  appointmentDate: [{ required: true, message: "请选择预约日期", trigger: "change" }],
  timeRange: [{ required: true, message: "请选择时间段", trigger: "change" }]
});


// 宠物列表
const pets = ref([]);
// 服务项目列表
const activities = ref([]);

// 监听主人姓名变化，获取宠物列表
watch(() => form.value.ownerName, async (newVal) => {
  if (newVal) {
    try {
      const response = await api.get("/users/findByName", {
        params: { name: newVal }
      });

      console.log(response.data);
      if (response.data) {
        const user = response.data;
        console.log(user.id)
        form.value.customerId = user.id;
        const petResponse = await api.get("/pets/selectBitPet", {
          params: { id: user.did }
        });
        pets.value = petResponse.data || [];
      } else {
        pets.value = [];
        form.value.customerId = "";
        ElMessage.warning("未找到该用户");
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
      ElMessage.error("获取用户信息失败");
    }
  } else {
    pets.value = [];
    form.value.petId = "";
    form.value.customerId = "";
  }
});

// 获取服务项目列表
const fetchActivities = async () => {
  try {
    const response = await api.get("/activity");
    activities.value = response.data.records || [];
  } catch (error) {
    console.error("获取服务项目失败:", error);
    ElMessage.error("获取服务项目失败");
  }
};

// 新增：计算当前选中的活动
const selectedActivity = computed(() => {
  return activities.value.find(a => a.id === form.value.activityId);
});

// 新增：时间选择器配置
const timePickerOptions = computed(() => {
  if (!selectedActivity.value) return {};

  return {
    disabledDate: (date) => {
      // 这里可以添加日期限制逻辑（如果需要）
      return false;
    },
    selectableRange: (() => {
      // 根据活动时长计算可选时间范围
      const duration = selectedActivity.value.duration;
      const startHour = 9; // 假设最早9点开始
      const endHour = 18;  // 假设最晚18点结束

      return `${startHour}:00 - ${endHour}:00`;
    })()
  };
});

const submitForm = async () => {
  try {
    await formRef.value.validate();

    // 检查服务时长
    if (selectedActivity.value && form.value.timeRange?.length === 2) {
      const [start, end] = form.value.timeRange;
      const minutes = dayjs(end, "HH:mm").diff(
          dayjs(start, "HH:mm"), 'minute'
      );

      if (minutes > selectedActivity.value.duration) {
        ElMessage.error('超过最大服务时长,请重新设置');
        return;
      }
    }

    // 检查服务项目是否已满
    const activity = activities.value.find(a => a.id === form.value.activityId);
    if (activity) {
      const countResponse = await api.get("/appointment/count", {
        params: { activityId: activity.id }
      });

      if (countResponse.data >= activity.maxNum) {
        ElMessage.error("该服务项目预约已满");
        return;
      }
    }

    const formattedDate = dayjs(form.value.appointmentDate).format('YYYY-MM-DD');

    // 检查时间段是否冲突
    const conflictResponse = await api.get("/appointment/checkConflict", {
      params: {
        activityId: form.value.activityId,
        date: form.value.appointmentDate,
        startTime: form.value.timeRange[0],
        endTime: form.value.timeRange[1]
      }
    });

    if (conflictResponse.data) {
      // 获取已存在的预约日期
      const existingAppointments = await api.get("/appointment", {
        params: {
          activityId: form.value.activityId,
          date: form.value.appointmentDate
        }
      });

      if (existingAppointments.data?.some(a => a.appointmentDate === form.value.appointmentDate)) {
        ElMessage.error("该日期和时间段已被预约");
      } else {
        ElMessage.error("该时间段已被其他日期的预约占用");
      }
      return;
    }



    if (conflictResponse.data) {
      ElMessage.error("该时间段已被预约");
      return;
    }

    console.log(form.value.petId)
    // 提交预约
    const appointmentData = {
      customerId: form.value.customerId, // 实际应用中应该是用户ID
      petId: form.value.petId,
      activityId: form.value.activityId,
      appointmentDate: formattedDate,
      startTime: form.value.timeRange[0],
      endTime: form.value.timeRange[1],
      notes: form.value.notes,
    };


    const createResponse = await api.post("/appointment", appointmentData);

    if (createResponse.success) {
      ElMessage.success("预约成功");
      dialogVisible.value = false;
      await fetchAppointment(); // 刷新列表
    } else {
      ElMessage.error(createResponse.msg || "预约失败");
    }
  } catch (error) {
    console.error("提交表单失败:", error);
    ElMessage.error(error.message || "提交表单失败");
  }
};


////////////////////////

// 预约数据
const appointmentData = ref([]);

// 分页信息
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
});

// 格式化日期显示
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '-';
  // 如果是appointmentDate（LocalDate）
  if (column.property === 'appointmentDate') {
    return dayjs(cellValue).format('YYYY-MM-DD');
  }

  // 如果是startTime或endTime（LocalTime）
  if (column.property === 'startTime' || column.property === 'endTime') {
    return dayjs(cellValue, 'HH:mm:ss').format('HH:mm');
  }

  return cellValue;
};

// 获取预约数据
const fetchAppointment = async () => {
  try {
    loading.value = true;
    const response = await api.get("/appointment", {
      params: {
        pageNo: pagination.value.pageNo,
        pageSize: pagination.value.pageSize
      }
    });

    if (response.code === 200 && response.success) {
      appointmentData.value = response.data.records || [];
      pagination.value.total = response.data.total || 0;
    } else {
      ElMessage.error(response.msg || "获取预约数据失败");
    }
  } catch (error) {
    console.error("获取预约数据失败:", error);
    ElMessage.error(error.message || "获取预约数据失败");
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  fetchAppointment();
};

const handleCurrentChange = (val) => {
  pagination.value.pageNo = val;
  fetchAppointment();
};

async function removeAppointment(row){
  ElMessageBox.confirm("是否确认删除要选中的行?","警告",{
    confirmButtonText:"确定",
    cancelButtonText:"取消",
    type:"warning"
  }).then(async () => {
    let resp = await api({
      url: "/appointment",
      method: "delete",
      data: row.id
    });
    if (resp.success){
      ElMessage.success("取消预约成功");
      await fetchAppointment();
    }else {
      ElMessage.error("取消预约失败");
    }
}).catch(()=>{
  });
}

onMounted(() => {
  fetchAppointment();
  fetchActivities();
});
</script>

<style scoped>

.action-bar {
  padding: 15px 20px;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
}

.full-screen-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.full-screen-table {
  flex: 1;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.pagination-footer {
  padding: 20px;
  background: #fff;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 60px;
}

/* 调整表头高度 */
:deep(.el-table__header th) {
  height: 60px;
}
</style>